<template>
  <div class="page-container">
    <div class="core-container">
      <!-- 左侧分类 -->
      <div class="menu-wrapper" ref="menuWrapper">
        <van-sidebar v-model="activeKey">
          <van-sidebar-item
            v-for="(item, index) in shopListObj"
            :key="index"
            :title="item.name"
            :badge="item.count > 0 ? item.count : ''"
            @click="selectMenu(index)"
          />
        </van-sidebar>
      </div>
      <!-- 右侧内容 -->
      <div class="foods-wrapper" ref="foodsWrapper">
        <ul>
          <!-- 一层渲染渲染系列 -->
          <li
            v-for="(item, index) in shopListObj"
            :key="index"
            class="food-list-hook"
          >
            <h1>{{ item.name }}</h1>
            <ul>
              <!-- 二层渲染渲染内容卡片 -->
              <van-card
                v-for="(food, foodIndex) in item.foods"
                :key="foodIndex"
                :desc="food.goodsDesc"
                :thumb="`http://47.122.115.10:5000/${food.imgUrl.slice(27)}`"
                @click="handleShopAll(index, food.id)"
              >
                <template #title="{}">
                  <div class="custom-title">{{ food.name }}</div>
                </template>
                <template #price="{}">
                  <div class="custom-price">${{ food.price.toFixed(2) }}</div>
                </template>
                <template #footer>
                  <div
                    style="
                      display: flex;
                      justify-content: end;
                      align-items: center;
                    "
                  >
                    <van-button
                      @click.stop="
                        decrement({ categoryId: index, foodId: food.id })
                      "
                      size="mini"
                      style="width: 0.4rem; height: 0.4rem; border-radius: 50%"
                      background-color="yellow"
                      ><span class="iconfont icon-jianshao"></span
                    ></van-button>
                    <div
                      style="
                        display: inline-flex;
                        justify-content: center;
                        align-items: end;
                        width: 0.3rem;
                        height: 100%;
                        font-size: 0.3rem;
                        margin: 0 0.2rem;
                      "
                    >
                      <span>{{ food.count }}</span>
                    </div>
                    <van-button
                      @click.stop="add({ categoryId: index, foodId: food.id })"
                      size="mini"
                      style="width: 0.4rem; height: 0.4rem; border-radius: 50%"
                      ><span
                        style="display: block; width: 100%"
                        class="iconfont icon-zengjia"
                      ></span
                    ></van-button>
                  </div>
                </template>
              </van-card>
            </ul>
          </li>
        </ul>
      </div>
    </div>
    <div class="shop" style="z-index: 2003" @click="handleShopList">
      <van-submit-bar
        style="background-color: black !important; padding: 0"
        :price="totalPrice * 100"
      >
        <template #default>
          <van-badge
            style="margin-top: 5px"
            :content="totalSelectedCount > 0 ? totalSelectedCount : ''"
            class="badge-style"
          >
            <span
              style="border-radius: 50%"
              class="iconfont icon icon-gouwuche"
              id="icon-shop"
            >
            </span>
          </van-badge>
        </template>
        <template #button>
          <van-button
            style="width: 2rem; height: 100%"
            type="danger"
            @click.stop="onSubmit"
          >
            去结算
          </van-button>
        </template>
      </van-submit-bar>
    </div>
    <!-- 弹出购物车 -->
    <van-popup
      z-index="2000"
      v-model="shopCarShow"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <template>
        <header
          style="
            box-sizing: border-box;
            padding: 0 10px;
            width: 100%;
            height: 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: rgb(237, 238, 242);
            color: rgb(195, 196, 198);
            font-size: 16px;
          "
        >
          <span>已选商品</span>
          <span @click="clearShop">清空</span>
        </header>
        <main style="padding: 0 10px">
          <ul>
            <li v-for="item in selectedItems" :key="item.id" class="shop_li">
              <span>{{ item.name }}</span>
              <div class="shop_right">
                <span class="span_price">￥{{ item.price }}</span>
                <div
                  style="
                    display: flex;
                    justify-content: end;
                    align-items: center;
                  "
                >
                  <van-button
                    @click="
                      decrement({
                        categoryId: item.categoryId,
                        foodId: item.id,
                      })
                    "
                    size="mini"
                    style="width: 0.4rem; height: 0.4rem; border-radius: 50%"
                    background-color="yellow"
                    ><span class="iconfont icon-jianshao"></span
                  ></van-button>
                  <div
                    style="
                      margin: 0 5px;
                      display: inline-flex;
                      justify-content: center;
                      align-items: end;
                      width: 0.3rem;
                      height: 100%;
                      font-size: 0.3rem;
                      margin: 0 0.2rem;
                    "
                  >
                    <span>{{ item.count }}</span>
                  </div>
                  <van-button
                    @click="
                      add({ categoryId: item.categoryId, foodId: item.id })
                    "
                    size="mini"
                    style="width: 0.4rem; height: 0.4rem; border-radius: 50%"
                    ><span
                      style="display: block; width: 100%"
                      class="iconfont icon-zengjia"
                    ></span
                  ></van-button>
                </div>
              </div>
            </li>
          </ul>
        </main>
      </template>
    </van-popup>
  </div>
</template>

<script type="text/ecmascript-6">
import BScroll from "@better-scroll/core";
import { Sidebar, SidebarItem } from "vant";
import { fetchGoodsList } from "../api/index";
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import { Dialog } from "vant";

export default {
  name:'shopView',
  components: {
    "van-sidebar": Sidebar,
    "van-sidebar-item": SidebarItem,
  },
  data() {
    return {
      activeKey: 0,
      goodsName: [],
      goodsList: [],
      menuScroll: null,
      foodsScroll: null,
      listHeight: [],
      scrollY: 0,
      shopCarShow: false,
    };
  },
  mounted() {
    this.fetchGoodsList();
    this.FetchGoodsList()
      .then(() => {
        console.log("数据加载完成", this.shopListObj);
        this.$nextTick(() => {
          this._initScroll();
          this._calculateHeight();
        });
      })
      .catch((error) => {
        console.error("数据加载失败", error);
      });
  },
  methods: {
    ...mapMutations(["add", "decrement", "setShopListObj"]),
    ...mapActions(["FetchGoodsList", "clearCart",'setSelectedFood']),
    //跳转详情页
    handleShopAll(categoryId,foodId){
      this.setSelectedFood({categoryId,foodId})
      this.$router.push({
        name:'详情页',
        query:{
          categoryId,
          foodId
        }
      })
    },
    //点击下方购物车
    handleShopList() {
      if (this.$store.getters.selectedItems[0]) {
        this.shopCarShow = !this.shopCarShow;
      }
    },
    onSubmit() {
      Dialog.confirm({
        title: "支付",
        message: `您需要支付${this.$store.getters.totalPrice}元`,
      })
        .then(() => {
          // on confirm
        })
        .catch(() => {
          // on cancel
        });
    },
    clearShop() {
      Dialog.confirm({
        title: "清空操作",
        message: `此操作不可撤销，请谨慎操作！`,
      })
        .then(() => {
          this.shopCarShow = false;
          this.clearCart();
          // location.reload()
        })
        .catch(() => {
          // on cancel
        });
    },
    async fetchGoodsList() {
      const res = await fetchGoodsList();

      this.goodsList = res.goodsList;
      this.goodsName = this.goodsList.map((ele) => ele.name);
    },
    _initScroll() {
      this.menuScroll = new BScroll(this.$refs.menuWrapper, {
        click: true,
      });
      this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
        probeType: 3,
        click: true,
      });

      this.foodsScroll.on("scroll", (pos) => {
        this.scrollY = Math.abs(Math.round(pos.y));
      });
    },
    _calculateHeight() {
      let height = 0;
      this.listHeight.push(height);
      const foodList =
        this.$refs.foodsWrapper.getElementsByClassName("food-list-hook");
      Array.from(foodList).forEach((item) => {
        height += item.clientHeight;
        this.listHeight.push(height);
      });
    },
    selectMenu(index) {
      if (!this.foodsScroll || !this.menuScroll) {
        return;
      }
      let foodList =
        this.$refs.foodsWrapper.getElementsByClassName("food-list-hook");
      let el = foodList[index];
      this.foodsScroll.scrollToElement(el, 300);
      this.activeKey = index;
    },
  },
  computed: {
    ...mapState(["num", "shopListObj"]),
    ...mapGetters(["totalPrice", "totalSelectedCount", "selectedItems"]),

    currentIndex() {
      for (let i = 0; i < this.listHeight.length; i++) {
        let height1 = this.listHeight[i];
        let height2 = this.listHeight[i + 1];
        if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
          return i;
        }
      }
      return 0;
    },
  },
  watch: {
    currentIndex(newIndex) {
      this.activeKey = newIndex;
      let menuList =
        this.$refs.menuWrapper.querySelectorAll(".van-sidebar-item");
      let el = menuList[newIndex];
      this.menuScroll.scrollToElement(el, 300, 0, -300); // 这里的参数可能需要根据实际情况调整
    },
    scrollY(newY) {
      let listHeight = this.listHeight;
      let index;
      for (let i = 0; i < listHeight.length - 1; i++) {
        if (newY >= listHeight[i] && newY < listHeight[i + 1]) {
          index = i;
          break;
        }
      }
      if (typeof index !== "undefined" && this.activeKey !== index) {
        this.activeKey = index;
      }
    },
  },
};
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
.page-container
  position relative
  min-height 100vh
  display flex
  flex-direction column

.core-container
  display flex
  flex 1
  .menu-wrapper
    flex 0 0 80px
    height 70vh // 修改后的高度
    overflow hidden
    background #f3f5f7
  .foods-wrapper
    flex 1
    height 70vh // 修改后的高度
    overflow hidden
    ul
      list-style none
      padding 0
      margin 0
      li
        list-style none
        h1
          line-height 50px
          padding-left 10px
          border-left 2px solid #0085ff
          font-size 16px
          color #0085ff
.custom-title
  font-size 0.4rem
  font-weight 600
.custom-price
  font-size 0.4rem
  color red
.van-submit-bar__price
  color: #b2a7a8;
  font-weight: 700;
  font-size: .3rem;
#icon-shop
  box-sizing content-box
  margin-bottom 1rem
  display block
  width 1rem
  height 1rem
  background-color rgb(43, 52, 59)
  text-align center
  line-height 1rem
  border-radius 50%
  font-size 0.5rem
  color rgb(139, 140, 140)
  border 5px solid black
.iconfont
  font-size .6rem
.shop_li
  display flex
  justify-content space-between
  align-items center
  width 100%
  height 50px
  border-bottom 1px solid rgb(228, 228, 228)
  span
    font-size 0.35rem
  .iconfont
    font-size .6rem
  .shop_right
    display flex
    .span_price
      margin-right 15px
      color red
.van-submit-bar__bar
  padding-right 0
</style>
